import {messages} from "share/common";
import React, { Component } from 'react'
import { connect } from 'react-redux'
import AdvancedTable from "components/advanced-table";
import DataHoc from "./data-hoc";
import httpFetch from "share/httpFetch";
import CheckModal from "containers/pay/template/check-modal";
import { message, Modal, Form, Input, Spin } from 'antd'
import paymentService from "../pay-workbench/pay-workbench.service";
import PayModal from "../pay-workbench/unpaid/pay-modal";

class WaitCheck extends Component {

  key = 'wait-check';

  state = {
    loading: false,
    remark: '',
    editRecord: {},
    visible: false,
    companyCombinedPayment: false,
    searchForm: this.props.getSearchForm(this.key)
  };

  componentWillMount = () => {
    const { setOfBooksId } = this.props.company;
    this.setState({ loading: true });
    paymentService.getOptions({ setOfBookId: setOfBooksId }).then(res => {
      this.setState({ loading: false, companyCombinedPayment: res.data.companyCombinedPayment });
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  service = (page, pageSize, searchParams) => {
    return httpFetch.post(`/payment/api/cash/bankPay/queryBatch`, { page, size: pageSize, ...searchParams, hasChecked: false, isPreChecked: false });
  };

  handlePass = record => {
    Modal.confirm({
      title: messages('finance-4.key88')/*复核通过？*/,
      content: messages('finance-4.key89')/*复核通过后，待付数据将推送银行进行支付，请确认是否需要支付？*/,
      okText: messages('finance-4.key85')/*复核通过*/,
      onOk: () => this.check(record)
    })
  };

  check = record => {
    let { paymentData } = record;
    let params = {
      batchNos: [record.batchNo],
      checkStatus: '01'
    };
    if (paymentData.draweeAccountType !== 'ALIPAY_LOGON_ID') {
      let uKey = this.props.checkBrowser(record.orderRequestNo);
      params.data = {
        requestSeqNo: record.orderRequestNo,
        oper: uKey.certInfo.split('@')[1],
        operSign: uKey.res
      };
    }
    this.setState({ loading: true });
    httpFetch.post('/payment/api/cash/bankPay/check', params).then(res => {
      const { data } = res;
      switch (data.batStatus) {
        case '01':
          message.error(data.message);
          this.setState({ loading: false });
          return;
        case '02':
          Modal.confirm({
            title: messages('finance-4.key90')/*重复风险警告*/,
            content: <div>
              <div>{messages('finance-4.key91')/*本次支付存在重复支付请求风险（同一批次中同一收款人账户同一交易金额出现多次），是否继续支付？*/}</div>
              <div style={{ color: 'red' }}>{messages('finance-4.key92')/*注：请勿直接关闭浏览器，否则将会导致数据错误*/}</div>
            </div>,
            onOk: () => this.handleContinuePay(data),
            onCancel: () => this.handleCancelContinue(data),
            cancelText: messages('finance-4.key93')/*取消支付*/
          });
          return;
        case '03':
          Modal.warning({
            title: messages('finance-4.key94')/*下单部分成功*/,
            content: messages('finance-4.key95')/*银企直联下单部分成功，存在部分数据校验失败，请在付款工作台-支付失败或退票页签中查看并重新发起支付。*/
          });
          return;
        default:
          message.success(messages('finance-4.key96')/*支付成功*/);
          data.aliPayUrl && (window.open(data.aliPayUrl));
          this.setState({ loading: false }, () => {
            this.advancedTableRef.getList();
          });
          return;
      }
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  handleContinuePay = data => {
    const { porderId, batchNo, orderRequestNo } = data;
    let uKey = this.props.checkBrowser(orderRequestNo);
    paymentService.continuePay({
      porderId,
      batchNo,
      data: {
        requestSeqNo: orderRequestNo,
        oper: uKey.certInfo.split('@')[1],
        operSign: uKey.res
      }
    }).then(() => {
      message.success(messages('finance-4.key96')/*支付成功*/);
      this.setState({ loading: false }, () => {
        this.advancedTableRef.getList();
      });
    }).catch(e => {
      this.setState({ loading: false }, () => {
        this.advancedTableRef.getList();
      });
      message.error(e.response.data.message);
    });
  };

  handleCancelContinue = data => {
    const { batchNo } = data;
    paymentService.cancelContinuePay({ batchNo }).then(() => {
      this.setState({ loading: false }, () => {
        this.advancedTableRef.getList();
      });
    }).catch(e => {
      this.setState({ loading: false }, () => {
        this.advancedTableRef.getList();
      });
      message.error(e.response.data.message);
    })
  };

  handleEdit = record => {
    this.setState({ editRecord: record }, () => {
      this.setState({ visible: true })
    });
  };

  handleReject = record => {
    Modal.confirm({
      title: messages('finance-4.key97')/*复核驳回？*/,
      content: <div>
        {messages('finance-4.key98')/*请确认对支付订单批次进行复核驳回操作，驳回后，可重新在付款工作台中发起支付*/}
        <Form.Item
          label={messages('finance-4.key63')/*备注temp*/}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          className={'new-form'}
          style={{ margin: '10px 0', padding: 0 }}
        >
          <Input placeholder={messages('finance-4.key70')/*请输入temp2*/} onChange={e => this.setState({ remark: e.target.value })}/>
        </Form.Item>
      </div>,
      okText: messages('finance-4.key99')/*确认*/,
      onOk: () => this.reject(record)
    })
  };

  reject = record => {
    const { remark } = this.state;
    httpFetch.post('/payment/api/cash/bankPay/check', {
      checkStatus: '00',
      batchNos: [record.batchNo],
      remark
    }).then(() => {
      this.setState({ loading: false, remark: '' }, () => {
        this.advancedTableRef.getList();
      });
    }).catch(e => {
      this.setState({ loading: false, remark: '' });
      message.error(e.response.data.message);
    })
  };

  handleOk = () => {
    this.setState({ visible: false }, this.advancedTableRef.getList);
  };

  render() {
    const { loading, visible, editRecord, companyCombinedPayment, searchForm } = this.state;
    const { getColumns } = this.props;
    return (
      <div style={{ height: 'calc(100vh - 110px)' }}>
        <Spin spinning={loading}>
          <AdvancedTable
            title={messages('finance-4.key84')/*待复核*/}
            tableName='wait-check'
            service={this.service}
            onRef={ref => this.advancedTableRef = ref}
            searchForm={searchForm}
            rowKey="id"
            columns={getColumns(this.key)}
          />
        </Spin>
        <PayModal
          radioValue={'WAIT_CHECK'}
          visible={visible}
          onCancel={() => { this.setState({ visible: false }) }}
          record={[editRecord]}
          companyId={editRecord.companyId}
          setOfBookId={editRecord.setOfBookId}
          onOk={this.handleOk}
          companyCombinedPayment={companyCombinedPayment}
        />
      </div>
    )
  }

}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

export default connect(mapStateToProps)(CheckModal(DataHoc(WaitCheck)))
